#include <ESP8266WiFi.h>
#include <PubSubClient.h>

WiFiClient espClient;
PubSubClient client(espClient);

const char* mqtt_server = "mqtt.hanxiaoxin.cn";            // MQTT Broker 地址
const int mqtt_port = 1883;
const char* mqtt_username = "home8266";
const char* mqtt_password = "314314314";

const char* subscribe_topic = "world";
const char* publish_topic   = "world";

unsigned long lastPublish = 0;

void mqttCallback(char* topic, byte* payload, unsigned int length) {
  Serial.print("receive topic: ");
  Serial.print(topic);
  Serial.print(" msg: ");
  String msg;
  for (unsigned int i = 0; i < length; i++) {
    msg += (char)payload[i];
  }
  Serial.println(msg);
}

void connectToMQTT() {
  while (!client.connected()) {
    String clientId = "esp8266-client-" + WiFi.macAddress();
    Serial.printf("connect MQTT Broker(ClientID=%s)...\n", clientId.c_str());
    if (client.connect(clientId.c_str(), mqtt_username, mqtt_password)) {
      Serial.println("MQTT connect success!");
      client.subscribe(subscribe_topic);
      Serial.printf("subscribe topic: %s\n", subscribe_topic);
      client.publish(publish_topic, "Hello from ESP8266!");
    } else {
      Serial.printf("connect failed,errorCode=%d,5s later retry...\n", client.state());
      delay(5000);
    }
  }
}

void listenMQTT(){
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(mqttCallback);
  connectToMQTT();
}

void handleMQTT(){
  client.loop();
}